package blog.common.log;

import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class LogAspect {

    @Around(" @annotation(LogAnnotation) ")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        long beginTime = System.currentTimeMillis();

        Object obj = pjp.proceed();

        Long time = System.currentTimeMillis() - beginTime;

        recordLog(pjp, time);

        return obj;
    }

    private void recordLog(ProceedingJoinPoint pjp, Long time) throws NoSuchMethodException {

/*        Class<?> clazz = pjp.getTarget().getClass();
        String methodName = pjp.getSignature().getName();

        Object[] args = pjp.getArgs();
        Class[] argsClass = new Class[args.length];

        for (int i = 0; i < args.length; i++) {
            argsClass[i] = args[i].getClass();
        }

        Method method = clazz.getMethod(methodName, argsClass);

        System.out.println(Thread.currentThread().getName() + "===> " + method.toString());*/

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);

        log.info("=====================log start================================");
        log.info("module:{}",logAnnotation.module());
        log.info("operation:{}",logAnnotation.operation());

        //请求的方法名
        String className = pjp.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method:{}",className + "." + methodName + "()");

//        //请求的参数
        Object[] args = pjp.getArgs();
        String params = JSON.toJSONString(args[0]);
        log.info("params:{}",params);

        //获取request 设置IP地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        log.info("ip:{}", ServletUtil.getClientIP(request,"Authorization"));

        log.info("excute time : {} ms",time);

        log.info("=====================log end================================");

    }
}
